<?php

namespace App\Recharge\Logic;

use App\Jobs\MerchantZuHeJob;
use App\Jobs\ZuheJob;
use App\Models\Mysql\CombinedOrders;
use App\Models\Mysql\CycleOrder;
use App\Models\Mysql\MerchantCombinedOrders;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Enums\ApiGroupEnum;
use App\Recharge\Exceptions\CyclePunch\OrderIsNotInRechargeException;
use App\Recharge\Exceptions\CyclePunch\OrderNotFoundException;
use App\Recharge\Library;
use Exception;
use Throwable;
use App\Traits\Create;
use Illuminate\Http\Request;
use App\Models\Mysql\XnOrder;
use App\Models\Admin\Supplier;
use Illuminate\Http\JsonResponse;
use App\Jobs\OrderCallbackNotify;
use Illuminate\Support\Facades\Log;
use App\Recharge\Traits\RechargeTraits;
use App\Recharge\Interfaces\ApiInterface;
use App\Models\Admin\InterfaceConfiguration;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


class ApiPriceNoticeLogic
{
    use RechargeTraits, Create;

    /**
     * @var Supplier
     */
    public Supplier $supplier;

    /**
     * @var ?ApiNotifyDataBean
     */
    public ?ApiNotifyDataBean $bean = null;

    /**
     * @var InterfaceConfiguration|null
     */
    public ?InterfaceConfiguration $api = null;

    /**
     * @param Request $request
     * @param string $en
     */
    public function __construct(public Request $request, public string $en)
    {
        $supplier = $this->request->attributes->get('supplier');
        if (!$supplier) {
            throw new NotFoundHttpException('未找到供应商');
        }
        $this->supplier = $supplier;
    }

    /**
     * @return JsonResponse|mixed
     */
    public function send(): mixed
    {
        try {
            $this->api = InterfaceConfiguration::query()->firstWhere('en', $this->en);
            if (!$this->api) {
                throw new Exception("未找到回调方法");
            }
            // 获取interface
            $interface = $this->obtainApiInterface($this->api);
            // 执行后续操作
            $this->executeCallable($interface);
            // 返回
            return $interface->apiNotifySuccess();

        } catch (Throwable $e) {

            return $this->errorResponse($e);
        }
    }

    /**
     * @param ApiInterface $interface
     * @return void
     */
    protected function executeCallable(ApiInterface $interface): void
    {
        try {
            $this->bean = $interface->price_notice($this->api, $this->request)->setApi($this->api);
            // 是否往下执行
            if (!$this->bean->isExecute()) {
                throw new Exception("不往下执行");
            }
            // 往下执行

        } catch (Throwable $e) {
            Log::channel('error')->error('价格回调执行异常', $this->throwable($e, [
                'request'   => $this->request->toArray(),
                'api'       => $this->api->toArray(),
            ]));
        }
    }


    /**
     * @param Throwable $e
     * @param array $merge
     * @return array
     */
    protected function throwable(Throwable $e, array $merge = []): array
    {
        $data = [
            'url'       => $this->request->getUri(),
            'request'   => $this->request->toArray(),
            'error'     => error2array($e),
        ];
        return array_merge($data, $merge);
    }

    /**
     * @param Throwable $e
     * @return JsonResponse
     */
    protected function errorResponse(Throwable $e): JsonResponse
    {
        Log::error('回调异常', $this->throwable($e));
        return response()->json(['code' => 500, 'message' => $e->getMessage()]);
    }
}
